#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

/*
O_RDONLY
O_WRONLY
O_RDWR
*/

/*
O_CREAT
O_TRUNC
*/

int main(int argc, char const *argv[])
{
    // wirte
    int fd = open("a.txt", O_RDWR | O_CREAT | O_TRUNC, 0666);
    // open("/dev/tty", O_RDWR | O_NOCTTY | O_NDELAY);
    if(fd < 0) {
        printf("%d行:", __LINE__);
        perror("open");
        return 0;
    }

    printf("请输入需要写入的字符串: ");
    char wirte_buf[1024] = "";
    fgets(wirte_buf, sizeof(wirte_buf), stdin);
    wirte_buf[strlen(wirte_buf) - 1] = 0;

    write(fd, wirte_buf, strlen(wirte_buf));

    close(fd);

    // read
    fd = open("a.txt", O_RDWR, 0666);
    char read_buf[1024]="";
    int len = read(fd, read_buf, sizeof(read_buf));
    if(len < 0) {
        printf("%d行:", __LINE__);
        fflush(stdout);
        perror("read");
        return 0;
    }
    printf("长度:%d 内容:%s\n", len, read_buf);

    close(fd);

    return 0;
}
